package secu;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.function.Consumer;

/**
 * MD5测试
 * @author ben
 * @date 2021-09-26 20:17:43 CST
 */
public class TestMd5 {

	public static Consumer<Object> cs = System.out::println;

	public static void main(String[] args) {
//		test1();
		
		test2();
	}

	/**
	 * 使用md5
	 * MD5算法产生于1991年
	 * @author ben
	 * @date 2021-09-26 20:55:51 CST
	 */
	public static void test1() {
		cs.accept("test1() start...");
		try {
			MessageDigest md5 = MessageDigest.getInstance("md5");
			cs.accept("md5=" + md5);
			cs.accept("md5=" + md5.getAlgorithm());
			cs.accept("md5=" + md5.getDigestLength());
			cs.accept("md5.provider=" + md5.getProvider());
			cs.accept("md5=" + md5.getProvider().getInfo());
			cs.accept("md5=" + md5.getProvider().getName());
			cs.accept("md5=" + md5.getProvider().getVersion());
			
			byte[] encoded = md5.digest();
			outputByteArr(encoded);

			String str1 = "abc";
			encoded = md5.digest(str1.getBytes());
			outputByteArr(encoded);
			
			
			final String salt = "salt";
			encoded = md5.digest((salt + str1).getBytes());
			outputByteArr(encoded);
			
		} catch (NoSuchAlgorithmException e) {
			cs.accept("发生异常：e=" + e.getMessage());
		}
	}

	/**
	 * 使用MD2
	 * MD2算法产生于1989年
	 * @author ben
	 * @date 2021-09-26 21:48:56 CST
	 */
	public static void test2() {
		cs.accept("test2() start...");
		try {
			MessageDigest md2 = MessageDigest.getInstance("md2");
			cs.accept("md2=" + md2);
			cs.accept("md2=" + md2.getAlgorithm());
			cs.accept("md2=" + md2.getDigestLength());
			cs.accept("md2.provider=" + md2.getProvider());
			cs.accept("md2=" + md2.getProvider().getInfo());
			cs.accept("md2=" + md2.getProvider().getName());
			cs.accept("md2=" + md2.getProvider().getVersion());
			
			byte[] encoded = md2.digest();
			outputByteArr(encoded);

			String str1 = "abc";
			encoded = md2.digest(str1.getBytes());
			outputByteArr(encoded);
			
			
			final String salt = "salt";
			encoded = md2.digest((salt + str1).getBytes());
			outputByteArr(encoded);
			
		} catch (NoSuchAlgorithmException e) {
			cs.accept("发生异常：e=" + e.getMessage());
		}
	}
	
	
	private static void outputByteArr(byte[] arr) {
		cs.accept("输出byte[] arr：length=" + arr.length);
		for (int i=0; i<arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		cs.accept("");
		for (int i=0; i<arr.length; i++) {
			System.out.printf("%02x ", arr[i]);
		}
		cs.accept("");
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<arr.length; i++) {
			sb.append(Integer.toHexString((0x000000FF & arr[i]) | 0xFFFFFF00).substring(6)).append(" ");
		}
		cs.accept(sb.toString());
	}

}
